import requests
import re
import os
if __name__ == "__main__":
    #创建一个文件夹保存图片
    if not os.path.exists('./qiutuLibs'):
        os.mkdir('./qiutuLibs')
    headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55'
    }
    url='https://www.qiushibaike.com/imgrank/page/{}/'

    for pageNum in range(1,14):
        #对应页码的url
        new_url = url.format(pageNum)
        print(new_url)
        #使用通用爬虫对url对应的一整张页面进行爬取
        page_text = requests.get(url=new_url,headers=headers).text

        #使用聚焦爬虫将页面中所有的图片进行解析/提取
        ex='<div class="thumb">.*?<img src="(.*?)" alt=.*?</div>'
        img_src_list = re.findall(ex,page_text,re.S)
        #print(img_src_list)
        for src in img_src_list:
            #拼接出完整的图片地址
            src = 'https:'+src
            #请求到图片的二进制数据
            img_data = requests.get(url=src,headers=headers).content
            #生成图片名称
            img_name = src.split('/')[-1]
            #图片存储的路径
            imgPath = './qiutuLibs/'+img_name
            with open(imgPath,'wb') as fp:
                fp.write(img_data)
                print(img_name,'下载成功！！！')
